from django.contrib.auth import login
from django.db import DatabaseError
from django.shortcuts import render,redirect
from django.views import View
from django import http
from django.urls import reverse
import re
from meiduo_mall.apps.users.models import User
from meiduo_mall.utils.response_code import RETCODE
# Create your views here.
class UsernameCountView(View):

    def get(self,request,username):
        '''
        :param request: 请求
        :param username: 用户名
        :return:
        '''
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','count':count})

class UserMobileCountView(View):
    def get(self,request,mobile):
        '''
        :param request: 请求
        :param mobile: 用户名
        :return:
        '''
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','count':count,'mobile':mobile})

class RegisterView(View):
    '''用户注册'''
    def get(self,request):
        """
        提供注册界面
        :param request: 请求对象
        :return: 注册界面
        """
        return render(request,'register.html')

    def post(self,request):
        '''
        实现用户注册业务逻辑
        :param request:接受表单参数，校验参数
        :return:返回响应结果
        '''
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        # 校验参数：前后端的校验需要分开，避免恶意用户越过前端逻辑发请求，要保证后端安全
        if not all([username,password,password2,mobile,allow]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except DatabaseError:
            return render(request,'register.html',{'register_errmsg':'注册失败'})

        # 实现登录状态保持
        login(request,user)
        return redirect(reverse('contents:index'))